package com.qfedu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.qfedu.dao.UserDao;
import com.qfedu.pojo.Brand;
import com.qfedu.pojo.Phone;
import com.qfedu.pojo.User;
import com.qfedu.service.PhoneService;
import com.qfedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PhoneService phoneService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/login")
    public String login(String username,String password, Model model,Integer pageNum){
        System.out.println(username);
        System.out.println(password);
        Gson gson = new Gson();
        String key ="redis_index_"+username;
        //查询缓存
        String json = stringRedisTemplate.boundValueOps(key).get();
        if (json == null || "".equals(json)){
            //缓存中没有数据，查询数据库，并写入缓存
            try {
                User login = userService.login(username, password);
                if (null == pageNum){
                    pageNum = 1;
                }
                PageHelper.startPage(pageNum,4);

                List<Phone> phones = phoneService.selectAll();
                PageInfo<Phone> pageInfo = new PageInfo<>(phones);
                model.addAttribute("pageInfo",pageInfo);
                List<Brand> strings = phoneService.selectAllBrand();
                model.addAttribute("strings",strings);
                System.out.println(strings);
                //写入缓存
                String tojson = gson.toJson(pageInfo);
                stringRedisTemplate.boundValueOps(key).set(tojson);
                return "index";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            //缓存中有数据，从缓存中取
            PageInfo pageInfo = gson.fromJson(json, PageInfo.class);
            model.addAttribute("pageInfo",pageInfo);
//            System.out.println("-----------------查询缓存-----------------");
            return "index";

        }
       return "login";
    }

    @RequestMapping("/rgister")
    public String rgister(User user){
        int rgister = userService.rgister(user);
        System.out.println(rgister);
        return "login";
    }
}
